<template>
  <view class="page">
    <view class="header" v-if="0">
      <view class="input-view">
        <uni-icon type="search" size="22" color="#666666"></uni-icon>
        <input class="input" type="text" placeholder="输入搜索关键词" :disabled="true"/>
      </view>
    </view>
    <view class="uni-list" v-if="list.length">

      <view class="uni-list-cell" v-for="(value,key) of list" :key="key">
        <uni-swipe-action :options="swipeData(value.no_read_num)" @click="swipeAction"
                          @opened="openedAction(key)">
          <view class="uni-media-list" @tap="goMessage(value.chat_id,key,value.no_read_num)">
            <view class="uni-media-list-logo">
              <image :src="staticPhoto + value.photo_path + '?_=' + imgRan" :lazy-load="true"
                     style="border-radius: 12upx;"/>
            </view>
            <view class="red_num">
              <uni-badge :text="value.no_read_num" type="error"/>
            </view>
            <view class="uni-media-list-body">
              <view class="uni-media-list-text-top">
                {{ value.show_name }}
                <view style="float: right;color: #8f8f94;font-size: 23upx;">
                  {{ timestampFormat(value.time) }}
                </view>
              </view>
              <view class="uni-media-list-text-bottom uni-ellipsis">
                {{ msgHandle(value.last_msg + '') }}
              </view>
            </view>

          </view>
        </uni-swipe-action>
      </view>
    </view>

    <view :class="['action_main animated',(action_menu ? 'bounceInDown' : 'bounceOutUp')]" v-show="showActionMenu"
          @tap="actionMain">
      <view class="action_base">

        <view class="sj"></view>

        <view class="action_item" @tap="goAction(0)">
          <view class="uni-media-list-logo action_icon">
            <text class="uni-icon uni-icon-chat"></text>
          </view>
          <text class="action_item_text">发起群聊</text>
        </view>

        <view class="action_item" @tap="goAction(1)">
          <view class="uni-media-list-logo action_icon">
			<text class="uni-icon uni-icon-personadd"></text>
          </view>
          <text class="action_item_text">添加好友</text>
        </view>
        <!-- #ifdef APP-PLUS -->
        <view class="action_item" @tap="goScanCode">
          <view class="uni-media-list-logo action_icon">
			  <text class="uni-icon uni-icon-scan"></text>
          </view>
          <text class="action_item_text">扫一扫</text>
        </view>
        <!-- #endif -->

        <view class="action_item" v-if="0">
          <view class="uni-media-list-logo action_icon">
            <image :src="'../../static/theme/default/onmessage/in_out.png'" :lazy-load="true"/>
          </view>
          <text class="action_item_text">收付款</text>
        </view>

      </view>
    </view>

  </view>
</template>

<script>

import uniIcon from '@dcloudio/uni-ui/lib/uni-icon/uni-icon.vue';
import uniBadge from '@dcloudio/uni-ui/lib/uni-badge/uni-badge.vue';
import uniSwipeAction from '@dcloudio/uni-ui/lib/uni-swipe-action/uni-swipe-action.vue'
import _hook from '../../util/_hook';
import _action from '../../util/_action';
import _data from '../../util/_data';
import ws from '../../util/websocket.js';
import message from '../../util/api/message';
import chat from '../../util/api/chat';
import animate from 'animate.css';

export default {
  components: {
    uniIcon,
    uniBadge,
    uniSwipeAction,
  },
  data() {
    return {
      list: [],
      list_index: '',
      action_menu: false,
      action_menu_num: 0,
    }
  },
  onShow() {
    console.log('chat index');
	ws.initWebSocket();
    _hook.routeTabBarHook();
    let _this = this;
    let socket_state = _data.data('socket_state');
    if (!socket_state) {
      uni.setNavigationBarTitle({
        title: '连接中...'
      })
    }
    uni.$on('socket_state', function (data) {
      if (data) {
        uni.setNavigationBarTitle({
          title: '消息'
        })
      } else {
        uni.setNavigationBarTitle({
          title: '连接中...'
        })
      }
    });
    /** 监听最新数据 */
    uni.$on('data_chat_list', function (data) {
      _this.list = data;
    });
    let chat_list = _data.localData('chat_list');
    /** 加载本地缓存数据，让页面秒速渲染出来 */
    if (chat_list) {
      _this.list = chat_list;
    } else {
      ws.getChatList();
    }
    _this.action_menu = false;
    _this.action_menu_num = 0;
  },
  onLoad() {

  },
  onHide() {
    uni.$off('socket_state');
    uni.$off('data_chat_list');
  },
  computed: {
    showActionMenu() {
      return this.action_menu_num > 0;
    },
    staticPhoto() {
      return _data.staticPhoto();
    },
    imgRan() {
      return Math.random();
    },
  },
  methods: {
    msgHandle(msg) {
      return msg.replace(/&lt;/g, '<');
    },
    timestampFormat(time) {
      return _action.timestampFormat(time);
    },
    goAction(type) {
      let path = '';
      switch (type) {
        case 0:
          path = '../friend/index_list?chat_id=0';
          break;
        case 1:
          path = '../friend/add';
          break;
        default:
          return;
      }
      uni.navigateTo({
        url: path,
        animationType: 'slide-in-bottom',
      });
    },
    onPullDownRefresh() {
      ws.getChatList();
      console.log('刷新会话列表成功\(^o^)/');
      setTimeout(function () {
        uni.stopPullDownRefresh();
      }, 100);
    },
    actionMain() {
      this.action_menu = false;
      this.action_menu_num++;
    },
    openedAction(key) {
      this.list_index = key;
    },
    swipeAction(e) {
      let _this = this,
          chat_id = _this.list[_this.list_index].chat_id;
      if (!chat_id) {
        return;
      }
      switch (e.index) {
        case 0:
          /** 标为未/已读 */
          message.read({chat_id, no_read_num: _this.list[_this.list_index].no_read_num}).then(res => {
            ws.getChatList();
          })
          break;
        case 1:
          /** 删除这条对话 */
          message.delete({chat_id}).then(res => {
            _data.localData(chat_id, null);
            ws.getChatList();
          });
          _this.list.splice(_this.list_index, 1)
          break;
        default:
          break;
      }
    },
    swipeData(no_read_num) {
      return [
        {
          text: (no_read_num ? '标为已读' : '标为未读'),
          style: {},
        },
        {
          text: '删除',
          style: {
            backgroundColor: 'rgb(255,58,49)',
          }
        }
      ];
    },
    goMessage(chat_id, key, no_read_num) {
      if (no_read_num > 0) {
        ws.getChatData({
          chat_id: chat_id,
          time: 0,
          is_up: 1,
        });
        this.list[key].no_read_num = 0;
        //_data.localData('chat_list', this.list);
        _action.setStatusTips();
        chat.updateNoRead(chat_id);
      }
      _data.localData('message_chat_id', chat_id);
      uni.navigateTo({
        url: './message?chat_id=' + chat_id,
      });
    },
    goScanCode() {
      let _this = this;
      uni.scanCode({
        success: function (res) {
          /** 验证必须是一个地址 */
          if (/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/.test(res.result)) {
            /** 打开新地址 */
            uni.navigateTo({
              url: '../push/web?url=' + encodeURIComponent(res.result),
            });
            return;
          }
          if (res.result.startsWith('profile://')) {
            uni.navigateTo({
              url: '../friend/detail?user_id=' + res.result.split('id=')[1] + '&is_type=3',
            });
            return;
          }
          if (res.result.startsWith('group://')) {
            uni.navigateTo({
              url: '../chat/message/mores?chat_id=' + res.result.split('id=')[1],
            });
            return;
          }
          /** 本应用页面 */
          if (new RegExp(_data.data('http_url')).test(res.result)) {
            if (res.result.match(/\/([a-z]+_[a-z]+)\/(.+)$/) && RegExp.$1 && RegExp.$2) { //特殊路由
              switch (RegExp.$1) {
                case 'chat_add':
                  uni.navigateTo({
                    url: '../friend/detail?user_id=' + RegExp.$2 + '&is_type=3',
                  });
                  break;
                case 'group_add':
                  let option = (RegExp.$2 + '').split('&');
                  uni.navigateTo({
                    url: '../chat/message/mores?chat_id=' + option[0]
                  });
                  break;
                default:
                  /** 打开新地址 */
                  uni.navigateTo({
                    url: '../push/web?url=' + encodeURIComponent(res.result),
                  });
                  break;

              }
            }
            uni.showModal({
              content: '二维码内容：' + res.result,
              showCancel: false,
            });
            return;
          }
          uni.showModal({
            content: '二维码内容：' + res.result,
            showCancel: false,
          });
        },
        fail(e) {
          uni.showToast({
            title: '扫码错误：' + JSON.stringify(e),
            duration: 2000,
          });
        },
      });
    },
  },
  watch: {
    list: {
      handler(newValue, oldValue) {
        console.log('chat_list change')
        _data.data('chat_list', newValue)
      },
      immediate: true,
      deep: true
    }
  },
  onNavigationBarButtonTap(e) {
    this.action_menu = !this.action_menu;
    this.action_menu_num++;
  },
}
</script>

<style>

.uni-media-list-logo {
  height: 85upx;
  width: 85upx;
}

.header {
  display: flex;
  flex-direction: row;
  padding: 10px 15px;
  align-items: center;
}

.input-view {
  display: flex;
  align-items: center;
  flex-direction: row;
  background-color: #e7e7e7;
  height: 30px;
  border-radius: 5px;
  padding: 0 10px;
  flex: 1;
}

.input {
  flex: 1;
  padding: 0 5px;
  height: 24px;
  line-height: 24px;
  font-size: 16px;
}

.red_num {
  position: absolute;
  height: 34upx;
  top: 7upx;
  left: 95upx;
  font-size: 23upx !important;
}

/**
.uni-media-list-body {
    height: auto;
}
*/

.uni-swipe-action {
  width: 750upx !important;
}

.action_main {
  position: fixed;

  top: 55px;

  /* #ifndef H5 */
  top: 15px;
  /* #endif */

  width: 750upx;
  height: 1080upx;
  z-index: 100;
}

.action_base {
  position: absolute;
  right: 15upx;
  width: 300upx;
  background: #36363d;
  border-radius: 10upx;
}

.sj {
  position: fixed;
  top: -15upx;
  width: 0;
  height: 0;
  right: 35upx;
  border-left: 20upx solid transparent;
  border-right: 20upx solid transparent;
  border-bottom: 20upx solid #36363d;
}

.action_item {
  color: #e5e5e5;
  height: 100upx;
  line-height: 100upx;
  margin-left: 45upx;
  border-bottom: 1px solid #3e3e3e;
}

.action_icon {
  width: 45upx;
  height: 45upx;
  display: inline-block;
  vertical-align: middle;
}

.action_item:last-child {
  border: none;
}

.action_item_text {
  font-size: 30upx;
}

</style>
